<template>
    <!-- <myCanvas></myCanvas> -->
    <canvas ref="canvas" class="myCanvas" :display="display" :width="width" :height="height"></canvas>
</template>

<script>
export default {
    name:"myCanvas",
    props:{
        //水印内容
        text:{
            type:String,
            default:"峰之鼎"
        },
        //fontStyle水印字体样式
        fontStyle:{
            type:Object,
            default:()=>({
                size:28,
                family:'Helvetica',
                color:"#000"
            })
        },
        rotate:{
            type:Number,
            default:-20
        },
        display:{
            type:Boolean,
            default:true
        },
        //透明度
        opacity:{
            type:Number,
            default:0.1
        },
        width:{
            type:[Number,String],
            default:600
        },
        height:{
            type:[Number,String],
            default:600
        }
    },
    data(){
        return {
            img:''
        }
    },
    mounted (){
        //DOM渲染后执行
        this.$nextTick(() =>{
            //创建水印节点
            this.init()
        })
    },
    methods:{
        createMark (){
            const canvas = document.createElement('canvas') 
            const ctx = canvas.getContext('2d')
            //设置cavans样式
            ctx.font = `${this.fontStyle.size}px ${this.fontStyle.family}`
            //设置字体大小样式
            console.log('this.fontStyle.size :>> ', this.fontStyle.size);
            //设置字体底线对齐绘制基线
            ctx.textBaseline = 'bottom'
            //设置字体颜色
            ctx.fillStyle = this.fontStyle.color
            //水印的偏转角度
            ctx.rotate (this.rotate * Math.PI / 180)
            ctx.translate(this.rotate / 2, 0)
            ctx.fillText(this.text, 200, 200)
            return canvas
         },
        init (){
            this.img = ''
            const canvas = this.$refs.canvas
            const ctx = canvas.getContext('2d')
            const pattern = ctx.createPattern(this.createMark(),'repeat')
            ctx.fillStyle = pattern
            ctx.fillRect(0,0,600,600)
            //设置图片的质量
            this.img = canvas.toDataURL('image/png', 1)
        }
    }
}
</script>

<style>
.myCanvas{
    /* 解决canvas做网页背景无法选取后面元素的问题 */
    pointer-events: none
}
</style>